package com.mms.controller.admin;

import com.mms.activemq.ConsumerService;
import com.mms.activemq.ProducerService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by dan3652@sina.com on 2017-03-01 10:32.
 */
@RestController
public class ActiveMqController {
/*
    //队列名gzframe.demo
    @Autowired
    private Destination demoQueueDestination;

    //队列消息生产者
    @Autowired
    private ProducerService producer;

    //队列消息消费者
    @Autowired
    private ConsumerService consumer;

    @RequestMapping(value="/producer",method= RequestMethod.GET)
    public Object producer(){
        JSONObject obj = new JSONObject();
        System.out.println("------------go producer");

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = dateFormat.format( now );
        System.out.println(time);
        obj.put("time", time);

        return obj;
    }

    @RequestMapping(value="/onsend")
    public Object producer(@RequestParam("message") String message) {
        JSONObject obj = new JSONObject();
        System.out.println("------------send to jms");
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<5;i++){
            producer.sendMessage(demoQueueDestination, message+i);
            sb.append(message+i);
        }
        obj.put("message",sb);
        return obj;
    }

    @RequestMapping(value="/receive")
    public Object queue_receive() throws JMSException {
        JSONObject obj = new JSONObject();
        System.out.println("------------receive message");

        TextMessage tm = consumer.receive(demoQueueDestination);
        obj.put("textMessage", tm.getText());

        return obj;
    }

    *//*
     * ActiveMQ Manager Test
     *//*
    @RequestMapping(value="/jms")
    public Object jmsManager() throws IOException {
        JSONObject obj = new JSONObject();
        System.out.println("------------jms manager");

        JMXServiceURL url = new JMXServiceURL("");
        JMXConnector connector = JMXConnectorFactory.connect(url);
        connector.connect();
        MBeanServerConnection connection = connector.getMBeanServerConnection();
        obj.put("connection",connection);
        return obj;
    }*/
}
